package com.maotai.llzhou.thread;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;
import com.maotai.llzhou.util.JSUtil;

/**
 * 登录并且抢购
 */
public class MaotaiQueryWuLiuThread extends Thread {
	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;

	public MaotaiQueryWuLiuThread(MaotaiService maotaiService,
			Map<String, Object> zhanghao, String ipAndPort) {
		super();
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		try {
			MaotaiWebCookie mwc = new MaotaiWebCookie();
			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
			if (zhanghao.get("auth") == null
					|| "".equals(zhanghao.get("auth"))) {
				// 先执行登录操作
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				zhanghao.put("day", "1");
				maotaiService.updateZhanghaoOrderItemUpdateTime(zhanghao);
				return;
			}
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
						
			mwc.setAuth(zhanghao.get("auth") + "");
			String timestamp = System.currentTimeMillis()+"";
			String sign = JSUtil.excuFunctionA(mwc.getAuth()+timestamp);
			mwc.setSign(sign);
			mwc.setTimestamp(timestamp);
			String orderId = zhanghao.get("orderId") + "";
			String orderNo = zhanghao.get("orderNo") + "";
			String order_item_url = MaotaiString.ORDER_ITEM_URL.replace("xxx", orderId);
			String order_item_referer_url = MaotaiString.ORDER_ITEM_REFERER_URL.replace("xxx", orderId);
			String wuliu_item_url = MaotaiString.WULIU_ITEM_URL.replace("xxx", orderId).replace("yyy", orderNo);
			String wuliu_item_referer_url = MaotaiString.WULIU_ITEM_REFERER_URL.replace("xxx", orderId).replace("yyy", orderNo);
			
			mwc = hcu.sendHttpGetProxy(order_item_url,
					mwc, config, order_item_referer_url);
			if(mwc.getContent()!=null){
				String return_str = mwc.getContent();
				if(mwc.getContent().contains("login")){
					zhanghao.put("loginstatus", "0");
					maotaiService.updateZhanghaoLoginStatus(zhanghao);
					zhanghao.put("day", "1");
					maotaiService.updateZhanghaoOrderItemUpdateTime(zhanghao);
					return;
				}
				//{"data":{"bussinessLogs":null,"commentCount":null,"delivery":{"address":"陕西省汉中市汉台区北关街道陈家营十字东塔北路(考试管理中心院内)学生资助管理中心6栋507室","addressId":"1182402047610344454","areaCode":"610702000000","areaName":"","cityCode":"610700000000","cityName":"","deliveryBearName":"买方","deliveryCompany":null,"deliveryCompanyLogo":null,"deliveryCompanyMobile":null,"deliveryCompanyName":null,"deliveryId":4,"deliveryIdName":"快递","deliveryMobile":"13309163596","deliveryName":"任才家","deliveryPhone":null,"deliveryType":1,"detailed":"北关街道陈家营十字东塔北路(考试管理中心院内)学生资助管理中心6栋507室","logisticsBear":null,"logisticsBearCode":null,"logisticsCompany":null,"logisticsCompanyDesc":null,"logisticsCost":null,"logisticsId":null,"orderId":"1182468599524182024","postcode":"","provinceCode":"610000000000","provinceName":"","remark":null,"returnApplyId":null,"sendImgUrl":null,"streetCode":null,"streetName":"","waybillNo":null},"invoice":{"bankAccount":"","createPerson":"13309163596","createTime":"2018-07-31 15:00:03","id":"1182468599540959232","invoiceContent":"明细","invoiceContentType":1,"invoiceNo":null,"invoiceTaxType":1,"invoiceTaxTypeName":"增值税普通发票","invoiceTitle":"任才家","invoiceTitleType":1,"invoiceTitleTypeName":"个人","invoiceType":2,"invoiceTypeName":"电子发票","invoiceUrl":null,"isGenerated":0,"isSend":1,"openBank":"","orderCreateTime":"2018-07-31 15:00:03","orderId":"1182468599524182024","orderNo":"T00153871367597135","orgName":null,"payAmount":1499.00,"receiverEmail":null,"receiverPhone":null,"registerAddress":"","registerPhone":"","taxCode":"","unitName":null,"updatePerson":"13309163596","updateTime":"2018-07-31 15:00:03"},"logisticsTrackings":[{"context":"您的订单由商家拣货完毕，已出库交付【顺丰】，运单号为【544480771261】","dateTime":"10:31:46","trackDay":"2018-08-01/星期三"},{"context":"系统已确认，付款成功","dateTime":"15:28:32","trackDay":"2018-07-31/星期二"},{"context":"您提交了订单，请等待商家系统确认","dateTime":"15:00:03","trackDay":"2018-07-31/星期二"}],"orderGifts":[],"orderItems":[{"actualSubtotalAmount":1499.00,"alReturnNum":0,"brandId":"1173664101769056256","canReturnNum":null,"catalogId":242,"createPerson":"13309163596","createTime":"2018-07-31 15:00:03","freightInsuranceFee":1499.00,"hasEvaluation":false,"hasReturn":null,"id":"1182468599530473474","imgUrl":"https://prod-oss.emaotai.cn/supplychain-dev/test/img/CyfkdnP5Fs.jpg","isPartialShipment":0,"itemCode":"741","itemDiscountedPrice":1499.00,"itemGifts":[],"itemId":"1180731799924468740","itemItem":false,"itemName":"【茅台商城预约购买】贵州茅台酒（新飞天）53%vol 500ml（商品编号：741）","itemNum":1,"itemPrice":1499.00,"itemTeamData":null,"itemTeamDtos":[],"itemType":1,"memberId":2135470,"orderId":"1182468599524182024","orderPayAmount":null,"platformDiscountPrice":null,"platformTotalDiscountPrice":0,"redAlertPrice":1065.00,"scanCodeInfo":["6929951750","001000114140155229"],"sellOut":false,"sellerId":520100258,"shopDiscountPrice":null,"shopId":"1173773178264259584","shopItemCode":"741","shopTotalDiscountPrice":0,"skuDesc":"酱香","skuId":"1180731799931808771","status":1,"statusName":"已上架","subtotalAmount":1499.00,"updatePerson":"13309163596","updateTime":"2018-07-31 15:00:03","voucherSubtotalAmount":null}],"orderMain":{"abortTime":null,"activityDiscountAmount":0.00,"allRefundSucc":false,"allRefunding":false,"auditStatus":null,"canPay":false,"canRefund":true,"canRepeatBuy":true,"canReturn":true,"cancelDesc":null,"cancelTime":null,"cancelType":null,"channelId":1,"channelName":"茅台商城","cityDeliverySendOut":null,"collectTime":"2018-08-04 17:26:53","commissionAmount":null,"couponAmount":0.00,"createPerson":"13309163596","createTime":"2018-07-31 15:00:03","deliverBeginTime":null,"deliverEndTime":null,"errorReason":null,"fetchCode":null,"fetchStatus":null,"financeExamineTime":null,"financeRejectReason":null,"finishTime":null,"freightAmount":0.00,"frozenStatus":0,"gatheringNum":null,"giftTotalAmount":null,"hasRefund":false,"hasReturn":false,"id":"1182468599524182024","inRejection":null,"interceptReason":null,"inventorySendOut":true,"isError":0,"isFetch":0,"isPartialShipment":0,"isQrBuy":0,"isSelfSupport":1,"isSettlement":0,"itemAmount":1499.00,"memberId":2135470,"memberNickName":null,"memberUsername":"13309163596","needFinanceAudit":0,"needVisitAudit":0,"obligationNum":null,"offlinePayMethod":null,"operateType":1,"operateTypeName":"普通","orderNo":"T00153871367597135","orderPayError":false,"orderPayIng":false,"orderTime":"2018-07-31 15:00:04","originalStatus":5,"parentId":null,"payAmount":1499.00,"payChannelName":"支付宝","payEndTime":"2018-08-01 15:00:03","payErrorReason":null,"payMethod":"ALIPAY","payMethodName":"支付宝","payOnlineOff":"在线支付","payTime":"2018-07-31 15:28:32","platformDiscountAmount":0.00,"pointDiscountAmount":0.00,"preH5Url":null,"preTreated":null,"priceSysOpen":null,"redAlertPriceOutOf":null,"refundNos":[],"remark":"","sellerId":520100258,"sellerRemark":"无备注","settlementMsg":null,"settlementStatus":null,"settletMentTime":null,"shippingTime":"2018-08-01 10:31:46","shopDiscountAmount":0.00,"shopId":"1173773178264259584","shopName":"茅台商城","sourceOrderNo":"T00153871367597135","sourceShopNo":"1173773178264259584","status":5,"statusName":"已签收","totalAlReturnNum":0,"totalDiscountAmount":0.00,"totalItemNum":1,"totalRealRefundAmount":0,"totalRealReturnAmount":null,"transactionType":1,"updatePerson":"13309163596","updateTime":"2018-07-31 15:00:03","visitExamineTime":null,"visitRejectReason":null},"packageDeliverys":[],"payMain":null,"refundMains":[],"returnItems":null,"shopInfo":{"areaCode":"520111000000","areaName":"花溪区","businessHours":"","channelId":1,"cityCode":"520100000000","cityName":"贵阳市","contactPerson":"茅台商城","contactPhone":"4001000799","countyCode":"520111000000","countyName":"花溪区","detailAddress":"翔明大厦","detailed":"翔明大厦","latitude":"26.615455","longitude":"106.651432","name":"茅台商城","provinceCode":"520000000000","provinceName":"贵州省","shopIntroduction":"茅台商城","status":3,"streetCode":null,"streetName":null,"type":10009},"vouchers":[]},"resultCode":0,"resultMsg":"success"}
				JSONObject data = JSONObject.parseObject(return_str).getJSONObject("data");
				//物流明细
				JSONArray logisticsTrackings = data.getJSONArray("logisticsTrackings");
				/*{
					"context": "您的订单由商家拣货完毕，已出库交付【顺丰】，运单号为【544480771261】",
					"dateTime": "10:31:46",
					"trackDay": "2018-08-01/星期三"
					}
				 * */
				if(logisticsTrackings!=null && logisticsTrackings.size()>0){
					String kuaidiitem = logisticsTrackings.getJSONObject(0).getString("context");
					zhanghao.put("kuaidiitem", kuaidiitem);
				}
				JSONObject orderMain = data.getJSONObject("orderMain");
				String status = orderMain.getString("status");
				String statusName = orderMain.getString("statusName");
				zhanghao.put("status", status);
				zhanghao.put("statusName", statusName);
				maotaiService.updateZhanghaoOrderItem(zhanghao);
			}
			//物流详细
			mwc = hcu.sendHttpGetProxy(wuliu_item_url,
					mwc, config, wuliu_item_referer_url);
			if(mwc.getContent()!=null){
				String return_str = mwc.getContent();
				if(mwc.getContent().contains("login")){
					zhanghao.put("loginstatus", "0");
					maotaiService.updateZhanghaoLoginStatus(zhanghao);
					zhanghao.put("day", "1");
					maotaiService.updateZhanghaoOrderItemUpdateTime(zhanghao);
					return;
				}
				JSONArray datas = JSONObject.parseObject(return_str).getJSONArray("data");
				if(datas==null || datas.size()==0){
					System.out.println(zhanghao.get("code")+"---暂无物流详细");
					return;
				}
				JSONObject data = JSONObject.parseObject(return_str).getJSONArray("data").getJSONObject(0);
				String kuaiditype = data.getString("logisticsCompanyName");//logisticsCompanyName"顺丰",
				String kuaidicode = data.getString("waybillNo");//"waybillNo": "544480771261"
				zhanghao.put("kuaiditype", kuaiditype);
				zhanghao.put("kuaidicode", kuaidicode);
			}
			System.out.println(zhanghao);
			maotaiService.updateZhanghaoOrderItem(zhanghao);
		}catch(Exception e ){
			e.printStackTrace();
			
			try {
				zhanghao.put("day", "1");
				maotaiService.updateZhanghaoOrderItemUpdateTime(zhanghao);
				
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
//				e1.printStackTrace();
			}
		}
	}
}
